package com.example.medicine.controller;

import com.example.medicine.Bean.book;
import com.example.medicine.Mapper.bookMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    private static final String UPLOADED_FOLDER = "D:/FileRecv/uploadImages/";
    @Autowired
    private bookMapper bookMapper;
//    @RequiresPermissions("书籍管理")
    @GetMapping("/")
    public List<book> getBookList(){
        log.info("getBookList获取书籍信息");
        return bookMapper.getall();
    }

    @RequiresPermissions("书籍管理")
    @PostMapping("/")
    public void insertBook(@RequestParam("book") String bookJson,
                           @RequestParam(value = "imageCover", required = false) MultipartFile imageCover,
                           @RequestParam(value = "imageRight", required = false) MultipartFile imageRight) throws IOException {
        log.info("insertBook添加书籍start");
        String imageCoverName = null, imageRightName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        book book = objectMapper.readValue(bookJson, book.class);

        if (imageCover != null && !imageCover.isEmpty())
            imageCoverName = fileLoad(imageCover);

        if (imageRight != null && !imageRight.isEmpty())
            imageRightName = fileLoad(imageRight);

        book.setBookCoverName(imageCoverName);
        book.setCopyRightMapName(imageRightName);

        bookMapper.insert(book);
        log.info("insertBook添加书籍end");
    }

    @RequiresPermissions("书籍管理")
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatchBook(@RequestParam("file") MultipartFile file) {
        log.info("insertBatchBook书籍批量导入");
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }

            List<book> bookList = new ArrayList<>();
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                book book = new book();
                for(int i=0;i<=6;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 -> book.setName(value);
                        case 1 -> book.setAuthor(value);
                        case 2 -> book.setPublisher(value);
                        case 3 -> book.setEdition(value);
                        case 4 -> book.setEditionTime(value);
                        case 5 -> book.setIsbn(value);
                        case 6 -> book.setMedicalDoctor(value);
                    }
                }
                bookList.add(book);
            }
            // 将数据批量插入数据库
            if (!bookList.isEmpty()) {
                bookMapper.batchInsertBooks(bookList);
                System.out.println("成功！");
            }
            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }

    @RequiresPermissions("书籍管理")
    @PutMapping("/")
    public void updateBook(@RequestParam("book") String bookJson,
                           @RequestParam(value = "imageCover", required = false) MultipartFile imageCover,
                           @RequestParam(value = "imageRight", required = false) MultipartFile imageRight) throws IOException {
        log.info("updateBook修改书籍start");
        String imageCoverName = null, imageRightName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        book book = objectMapper.readValue(bookJson, book.class);

        if (imageCover != null && !imageCover.isEmpty())
            imageCoverName = fileLoad(imageCover);

        if (imageRight != null && !imageRight.isEmpty())
            imageRightName = fileLoad(imageRight);
        book.setBookCoverName(imageCoverName);
        book.setCopyRightMapName(imageRightName);
        bookMapper.updateNone(book);
        if (imageCover != null && !imageCover.isEmpty())
            bookMapper.updateCover(book);
        if (imageRight != null && !imageRight.isEmpty())
            bookMapper.updateRight(book);
        log.info("updateBook修改书籍end");
    }
    private String fileLoad(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename();    //获取原始的文件名
        //用UUID作为新文件名，扩展名不变  避免同名覆盖
        String newName = UUID.randomUUID()+ "." + fname.substring(fname.lastIndexOf(".")+1);
        File dest_file = new File( UPLOADED_FOLDER + newName );
        file.transferTo(dest_file);
        return newName;
    }
    @RequiresPermissions("书籍管理")
    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable String id){
        log.info("deleteBook删除书籍");
        bookMapper.deleteById(id);
    }
}